package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"sync"
	"time"

	"grpc-go-demo/echo"

	"google.golang.org/grpc"
)

func main() {
	connect, err := grpc.Dial("localhost:8080", grpc.WithInsecure())
	if err != nil {
		log.Fatalln(err.Error())
	}
	defer connect.Close()

	client := echo.NewEchoClient(connect)

	var wg sync.WaitGroup

	stream, err := client.BidirectStreamEcho(context.Background())
	if err != nil {
		log.Fatalln(err.Error())
	}

	wg.Add(1)
	go func() {
		defer wg.Done()
		for {
			req, err := stream.Recv()
			if err == io.EOF {
				fmt.Println("server closed")
				break
			}
			if err != nil {
				continue
			}
			fmt.Println("receive data:", req.GetMessage())
		}
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()

		for i := 0; i < 2; i++ {
			err := stream.Send(&echo.EchoRequest{Message: "hello world"})
			if err != nil {
				log.Println(err.Error())
			}
			time.Sleep(time.Second)
		}
		err := stream.CloseSend()
		if err != nil {
			log.Println(err.Error())
			return
		}
	}()

	wg.Wait()

}
